package com.library.service.impl;

import com.library.dao.BookDao;
import com.library.entity.Book;
import com.library.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookDao bookDao;

    @Override
    @Transactional
    public boolean addBook(Book book) {
        // 检查ISBN是否已存在
        Book existingBook = bookDao.findByIsbn(book.getIsbn());
        if (existingBook != null) {
            return false;
        }
        
        book.setAvailableQuantity(book.getTotalQuantity());
        return bookDao.insert(book) > 0;
    }

    @Override
    public Book getBookById(Integer id) {
        return bookDao.findById(id);
    }

    @Override
    public Book getBookByIsbn(String isbn) {
        return bookDao.findByIsbn(isbn);
    }

    @Override
    public List<Book> getAllBooks() {
        return bookDao.findAll();
    }

    @Override
    public List<Book> searchBooks(String title, String author, Integer categoryId) {
        return bookDao.findByCondition(title, author, categoryId);
    }

    @Override
    @Transactional
    public boolean updateBook(Book book) {
        return bookDao.update(book) > 0;
    }

    @Override
    @Transactional
    public boolean deleteBook(Integer id) {
        return bookDao.delete(id) > 0;
    }

    @Override
    @Transactional
    public boolean decreaseAvailableQuantity(Integer bookId) {
        Book book = bookDao.findById(bookId);
        if (book != null && book.getAvailableQuantity() > 0) {
            return bookDao.updateAvailableQuantity(bookId, -1) > 0;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean increaseAvailableQuantity(Integer bookId) {
        Book book = bookDao.findById(bookId);
        if (book != null && book.getAvailableQuantity() < book.getTotalQuantity()) {
            return bookDao.updateAvailableQuantity(bookId, 1) > 0;
        }
        return false;
    }
}